package com.example.getchatimg;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.Toolbar;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author 5804
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {

    private static final String TAG = "MainActivity";
    private ImageView imageView;
    @SuppressLint("SdCardPath")
    private static final String FILE_PATH = "/sdcard/Android/data/com.tencent.mobileqq/Tencent/MobileQQ/chatpic/chatimg";
    @SuppressLint("SdCardPath")
    private static final String FILE_TIM_PATH = "/sdcard/Android/data/com.tencent.tim/Tencent/Tim/chatpic/chatimg";
    @SuppressLint("SdCardPath")
    private static final String IMG_PATH = "/sdcard/QQ闪照/";
    private Handler mBackgroundHandler;
    private static final int FLAG_QQ_EXIST = 1;
    private static final int FLAG_TIM_EXIST = 2;
    private int existFlag = 0;
    File file = new File(FILE_PATH);
    File timFile = new File(FILE_TIM_PATH);
    File imgFile = new File(IMG_PATH);
    File imgSavePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();
        setDecorView();
        checkQQ();
        startBackgroundThread();
        imageView = findViewById(R.id.iv);
        Button btn_getqq = findViewById(R.id.bt_qq);
        Button btn_gettim = findViewById(R.id.bt_tim);
        btn_getqq.setOnClickListener(this);
        btn_gettim.setOnClickListener(this);
        imageView.setOnLongClickListener(this);
    }


    /**
     * 检测手机中是否存在相关文件夹
     */
    private void checkQQ() {
        if (file.exists()) {
            existFlag += FLAG_QQ_EXIST;
            Toast.makeText(MainActivity.this, "已检测到QQ", Toast.LENGTH_SHORT).show();
        }
        if (timFile.exists()) {
            existFlag += FLAG_TIM_EXIST;
            Toast.makeText(MainActivity.this, "已检测到TIM", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取目录下所有文件(按时间排序)
     *
     * @param path
     * @return
     */

    public static List<File> listFileSortByModifyTime(String path) {
        List<File> list = getFiles(path, new ArrayList<>());
        if (list.size() > 0) {
            Collections.sort(list, (file, newFile) -> Long.compare(newFile.lastModified(), file.lastModified()));
        }
        return list;
    }

    /**
     * 获取目录下所有文件
     *
     * @param realpath
     * @param files
     * @return
     */
    public static List<File> getFiles(String realpath, List<File> files) {
        File realFile = new File(realpath);
        Log.d("nmsl",realpath);
        if (realFile.isDirectory()) {
            File[] subFiles = realFile.listFiles();
            for (File file : Objects.requireNonNull(subFiles)) {
                if (file.isDirectory()) {
                    getFiles(file.getAbsolutePath(), files);
                } else {
                    files.add(file);
                }
            }
        }
        return files;
    }

    /**
     * 将本地的图片文件转换为Bitmap
     *
     * @param url
     * @return
     */
    public static Bitmap getLocalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            //把流转化为Bitmap图片
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bt_qq) {
            if ((existFlag & 1) == 1) {
                List<File> list = listFileSortByModifyTime(FILE_PATH);
                imageView.setImageBitmap(getLocalBitmap(list.get(0).getAbsolutePath()));
            } else {
                Toast.makeText(MainActivity.this, "未检测到QQ", Toast.LENGTH_SHORT).show();
            }
        } else if (v.getId() == R.id.bt_tim) {
            if ((existFlag >> 1) == 1) {
                List<File> list = listFileSortByModifyTime(FILE_TIM_PATH);
                imageView.setImageBitmap(getLocalBitmap(list.get(0).getAbsolutePath()));
            } else {
                Toast.makeText(MainActivity.this, "未检测到TIM", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onLongClick(View v) {
        if (v.getId() == R.id.iv) {
            if (!imgFile.exists()) {
                imgFile.mkdirs();
            }
            String date = System.currentTimeMillis() + ".jpg";
            imgSavePath = new File(imgFile, date);
            imageView.buildDrawingCache(true);
            imageView.buildDrawingCache();
            Bitmap bitmap = imageView.getDrawingCache();
            mBackgroundHandler.post(new ImageSaver(bitmap, imgSavePath));
            imageView.setDrawingCacheEnabled(false);
            Toast.makeText(MainActivity.this, "已为你保存至" + IMG_PATH + date, Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    /**
     * 获取权限
     */
    private void checkPermission() {
        SharedPreferences gtd = getSharedPreferences("data", MODE_PRIVATE);
        boolean flag = gtd.getBoolean("canApply", false);
        if (!flag) {
            AndPermission.with(this)
                    .runtime()
                    .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                    .onGranted(permissions -> {
                        //Storage permission are allowed.
                        Toast.makeText(MainActivity.this, "已获取权限", Toast.LENGTH_SHORT).show();
                        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                        editor.putBoolean("canApply", true);
                        editor.apply();
                    })
                    .onDenied(permissions -> {
                        //Storage permission are not allowed.
                        Uri packageURI = Uri.parse("package:" + MainActivity.this.getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(MainActivity.this, "没有权限无法获取信息呦", Toast.LENGTH_LONG).show();
                    })
                    .start();
        }
    }


    /**
     * 将捕获到的图像保存到指定的文件中
     */
    private static class ImageSaver implements Runnable {

        private final Bitmap mBitmap;
        private final File mFile;

        ImageSaver(Bitmap bitmap, File file) {
            this.mBitmap = bitmap;
            this.mFile = file;
        }

        @Override
        public void run() {
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(mFile));
                mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 开启HandlerThread
     */
    private void startBackgroundThread() {
        HandlerThread mBackgroundThread = new HandlerThread("imageBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }

    /**
     * 设置取消标题栏 状态栏 及 导航栏
     */
    private void setDecorView() {
        //如果API大于30
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            getWindow().setDecorFitsSystemWindows(false);
            WindowInsetsController controller = getWindow().getInsetsController();
            if (controller != null) {
                controller.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
                controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }

    }





}